package middlewares

import (
  "fmt"
  "github.com/gin-gonic/gin"
  "io"
  "log"
  "os"
  "path"
  "time"
)

var Logger *log.Logger

func LoggerHandler() gin.HandlerFunc {
  return func(c *gin.Context) {
    now := time.Now()
    logFilePath := ""
    if dir, err := os.Getwd(); err == nil {
      logFilePath = dir + "/logs/"
    }
    if err := os.MkdirAll(logFilePath, 0777); err != nil {
      fmt.Println(err.Error())
    }
    logFileName := now.Format("2006-01-02") + ".log"
    // 日志文件
    fileName := path.Join(logFilePath, logFileName)
    if _, err := os.Stat(fileName); err != nil {
      if _, err := os.Create(fileName); err != nil {
        fmt.Println(err.Error())
      }
    }
    // 写入文件
    src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
    if err != nil {
      fmt.Println("err", err)
    }

    // 实例化
    l := &log.Logger{}

    // 设置输出
    l.SetOutput(io.MultiWriter(src, os.Stdout))

    l.SetFlags(log.LstdFlags | log.Llongfile)

    Logger = l

    // 请求方式
    reqMethod := c.Request.Method

    // 请求路由
    reqUri := c.Request.RequestURI

    // 状态码
    statusCode := c.Writer.Status()

    // 请求IP
    clientIP := c.ClientIP()

    Logger.Printf("| %s | %3d | %15s | %s | %s |",
      time.Now().Format("2006-01-02 15:04:05"),
      statusCode,
      clientIP,
      reqMethod,
      reqUri,
    )
  }
}
